import { reject } from 'lodash'

const readFile = (path) => {
  return new Promise((resolve) => {
    plus.io.requestFileSystem(
      plus.io.PUBLIC_DOCUMENTS,
      (fs) => {
        //请求文件系统
        //请求地址文件  '/storage/emulated/0/config.txt'为根目录  '/config.txt'为/storage/Android/data/io.dcloud.HBuilder（包名）/documents/config.js
        fs.root.getFile(
          path,
          {
            //当文件不存在时创建
            create: false,
          },
          (fileEntry) => {
            fileEntry.file(function (fs) {
              getFileContent(fs).then((err) => {
                resolve('ok')
              })
            })
          },
          (error) => {
            console.log('2获取文件失败', error)
            plus.nativeUI.toast('获取文件失败,请重启应用', {
              background: '#ffa38c',
            })
            resolve(-1)
            return
          }
        )
      },
      (e) => {
        console.log('1请求文件系统失败', e.message)
        plus.nativeUI.toast('请求系统失败,请重启应用', {
          background: '#ffa38c',
        })
        return
      }
    )
  })
}

const getStaticFiles = () => {
  return new Promise((resolve, reject) => {
    plus.io.resolveLocalFileSystemURL(
      '_doc/cable',
      (fs) => {},
      (e) => {
        alert('Request file system failed: ' + e.message)
      }
    )
  })
}

async function tryread(fs, begin, end) {
  return new Promise((resolve) => {
    let reader = new plus.io.FileReader()
    reader.onloadend = function (e) {
      let str = e.target.result
      let value = null
      resolve(str)
    }
    reader.onerror = function (e) {
      console.log('读取失败')
      resolve('')
    }
    reader.readAsText(fs.slice(begin, end), 'utf-8')
    fs.close()
  })
}

async function tryparseone(fs, begin, end) {
  let str = await tryread(fs, begin, end)
  let strshort = str //.replace(/\n|\r/g, '');
  // if (strshort[strshort.length - 1] == ',') {
  // 	strshort = strshort.slice(0, strshort.length - 1);
  // }
  try {
    const value = JSON.parse(strshort)
    if (value && typeof value == 'object') {
      return {
        str: str,
        isjson: 'object',
        value: value,
      }
    }
    return {
      str: str,
      isjson: 'string',
      value: value,
    }
  } catch (error) {
    return {
      str: str,
      isjson: 'continue',
      value: null,
    }
  }
}

async function getFileContent(fs) {
  let begin = 1
  let tolen = 2
  let strexists = true
  let issubstation = false
  let i = 0
  var subs = []
  let ttlen = fs.size
  while (tolen < ttlen) {
    // let thelast = await tryread(fs, tolen, tolen);
    // console.log('the last', thelast, tolen);

    // while (tolen < ttlen && thelast != '\n') {

    // 	tolen++;
    // 	thelast = await tryread(fs, tolen, tolen);
    // 	// console.log('the last',thelast,tolen);
    // }
    // console.log('the last', thelast, tolen);

    const { str, isjson, value } = await tryparseone(fs, begin, tolen)
    if (tolen % 1000 == 0 || isjson != 'continue') {
      console.log(
        'isjson',
        isjson,
        subs.length,
        issubstation,
        'begen:' + begin + '==>' + tolen + '@@' + i,
        '\n开始字串是:\n'
      )
      console.log(str)
    }
    if (subs.length > 2) {
      console.log('subs:', subs)
      break
    }
    i++
    // if(i>4000) break;
    //console.log(issubstation);
    //console.log("str:"+str); console.log("trim:"+'"Substation":['.trim())
    var iscontinue = false
    var strtrim = str.trim()
    switch (strtrim) {
      case ',':
        begin = tolen + 1
        tolen = begin + 1
        iscontinue = true
        break
      case '],': // 跳过
        begin = tolen + 1
        tolen = begin + 1
        iscontinue = true
        break
      case '"Substation":[':
        issubstation = 'substation'
        begin = tolen + 1 //应该 也要加1吧？试试看了.
        tolen = begin + 1
        iscontinue = true
        break
      case '"Task":[':
        issubstation = 'task'
        begin = tolen + 1 //应该 也要加1吧？试试看了.
        tolen = begin + 1
        iscontinue = true

        break
      case '"Equipment":[':
        issubstation = 'equipment'
        begin = tolen + 1 //应该 也要加1吧？试试看了.
        tolen = begin + 1
        iscontinue = true

        break
      case '"Channel":[':
        issubstation = 'channel'
        begin = tolen + 1 //应该 也要加1吧？试试看了.
        tolen = begin + 1
        iscontinue = true

        break
      case '"CableSection":[':
        issubstation = 'cablesection'
        begin = tolen + 1 //应该 也要加1吧？试试看了.
        tolen = begin + 1
        iscontinue = true

        break
      case '"CableWell":[':
        issubstation = 'cablewell'
        begin = tolen + 1 //应该 也要加1吧？试试看了.
        tolen = begin + 1
        iscontinue = true

        break
    }
    if (iscontinue) continue
    switch (isjson) {
      case 'object':
        begin = tolen + 1 //去掉后面的 逗号
        const nextchar = await tryread(fs, begin + 1, begin + 1)
        console.log('now....', nextchar, begin)
        if (nextchar == ',') begin = begin + 1
        // 保存value

        tolen = begin + 1
        switch (issubstation) {
          case 'substation':
            subs.push(value)
            // save to substation;
            break
          case 'task':
            // 保存treedata就好了
            break
          case 'equipement':
            break
          case 'channel':
            break
          case 'cablesection':
            break
          case 'cablewell':
            break
        }

        break
      case 'string':
        tolen = tolen + 1
        break
      case 'continue':
        tolen = tolen + 1
        break
    }
  }
}

async function tryparseone2(fs, begin, tolen) {
  return new Promise((resolve) => {
    let reader = new plus.io.FileReader()
    reader.onloadend = function (e) {
      let str = e.target.result
      resolve(str)
    }
    reader.readAsText(fs.slice(begin, begin + tolen), 'utf-8')
  })
}

export { readFile }
